<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>调拨</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //是否临时保存
        var temporary = Ext.create('Ext.form.field.Hidden', {
          name: 'temporary',
          value: 0
        });
        
        //备注
        var desc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '95%'
        });
        
        //所有仓库
        var fromWarehouse = Ext.create('Ext.form.ComboBox', {
          store: warehouseStore,
          fieldLabel: '调出仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'from_warehouse_id',
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          minChars: 0,
          triggerAction:'all'
        });

        var toWarehouse = Ext.create('Ext.form.ComboBox', {
          store: warehouseStore,
          fieldLabel: '到仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'to_warehouse_id',          
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          minChars: 0,
          editable:false          
        });

        //调拨日期
        var actionDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '调拨日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "调拨日期必须选择",
          emptyText: '请选择日期...'
          //anchor: '50%'
        });
        
        //产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
          store: productStore,
          emptyText: '请选择...',
          displayField: 'name',
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 10,
          minChars: 0,
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
            }
          }
        });

        productCBB.on('select', function(combo, record, index) {
          var records = transferOrderDetailGrid.getSelectionModel().getSelection();
          var transferRecord = records[0];
          if (!transferRecord) {
            return false;
          }
          
          if (isDuplicateByProduct(transferOrderDetailDS,records[0].get('id'),transferRecord.id)){
            //删除当前记录
            transferOrderDetailDS.remove(transferRecord);
          }else{
            if (transferRecord.get('product_id') != record[0].get('id')){
              transferRecord.set('number',record[0].get('number'));
              transferRecord.set('spec',record[0].get('spec'));
              transferRecord.set('unit',record[0].get('unit'));
              transferRecord.set('quantity',1);
              transferRecord.set('stock_quantity',0);
              transferRecord.set('product_id',record[0].get('id'));
              transferRecord.set('is_suit',record[0].get('is_suit'));
            }
          }
        });


        //--------------------------------------------------------------------------
        //入库Grid Store

        var transferOrderDetailDS = Ext.create('Ext.data.Store', {
          //autoDestroy : true,
          model : 'TransferOrderDetailModel',
          proxy : {
            type : 'ajax',
            //url : '/admin/getAllSysActions',
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          }
        });        

        //生成要订单的产品的Grid
        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
          clicksToEdit: 1
        });
        
        //生成要订单的产品的Grid
        var transferOrderDetailGrid = Ext.create('Ext.grid.Panel', {
          store: transferOrderDetailDS,
          plugins: [cellEditing],
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              field: productCBB,
              width: 370
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 90
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 1
              }),
              width: 50
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '库存数量',
              align: 'right',
              dataIndex: 'stock_quantity',
              width: 60
            }],
          selModel :Ext.create('Ext.selection.CheckboxModel'),
          width: 930,
          height: 375,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                var record = Ext.ModelManager.create({
                  product_name: '请选择产品'
                }, transferOrderDetailGrid.getStore().model);
                transferOrderDetailDS.insert(0, record);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var records = transferOrderDetailGrid.getSelectionModel().getSelection();
                cellEditing.cancelEdit();
                transferOrderDetailDS.remove(records);
                
              }
            }]
        });

        //效验库存按钮
        var checkStockButton = Ext.create('Ext.Button', {
          text: '检查库存',
          tooltip: '检查库存',
          iconCls: 'icon-save',
          handler: function(){
            if(transferFormPanel.form.isValid()){
              //同仓库不能调拨
              if(fromWarehouse.getValue() == toWarehouse.getValue() ){
                Ext.MessageBox.alert('提示', "同仓不能调拨！");
              }else{
                //没有添加产品，则提示
                if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您还没有选择有效的产品或选择的产品数量为0！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                }

                var productsJsonStr = gridStoreToJson(transferOrderDetailDS,rejectKeyArray);
                if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您还没有选择有效的产品或选择的产品数量为0！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                }
                var allJsonStr = transferFormPanel.getForm().getValues();
                allJsonStr = Ext.JSON.encode(allJsonStr);
                allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
                allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                //alert(allJsonStr);
                Ext.Ajax.request({
                  url : '/transfer_order/check_stock',
                  success : function (result, request) {
                    //alert(Ext.JSON.decode(result.responseText).length);
                    var jsonArray = Ext.JSON.decode(result.responseText);
                    var records = transferOrderDetailDS.getRange(0,transferOrderDetailDS.getCount());
                    for (var i = 0 ; i< jsonArray.length;i++){                      
                      for(var j = 0; j< records.length ;j++){
                        var record = records[j];
                        if(record.get('product_id') == jsonArray[i].product_id){
                          record.set('stock_quantity',jsonArray[i].quantity);
                          break;
                        }
                      }
                    }
                  },
                  failure : function (result, request){
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "通讯失败，请从新操作",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  },
                  method : 'POST',
                  params : {
                    data : Ext.JSON.encode(allJsonStr),
                    authenticity_token: authToken.getValue()
                  }
                });
              }
            }
          }
        });

        //提交按钮
        var transferButton = Ext.create('Ext.Button', {
          text: '提交',
          tooltip: '提交',
          iconCls: 'icon-save',
          handler: function(){
            if(transferFormPanel.form.isValid()){
              //同仓库不能调拨
              if(fromWarehouse.getValue() == toWarehouse.getValue() ){
                Ext.MessageBox.alert('提示', "同仓不能调拨！");
              }else{
                //没有添加产品，则提示
                if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您还没有选择有效的产品或选择的产品数量为0！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                }
                
                var productsJsonStr = gridStoreToJson(transferOrderDetailDS,rejectKeyArray);
                if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您还没有选择有效的产品或选择的产品数量为0！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                }

                //再取得一次库存
                checkStockButton.handler();
                //检查一下，如果要调拨的货比仓库的库存还要，就提示
                var records = transferOrderDetailDS.getRange(0,transferOrderDetailDS.getCount());
                for (var i = 0 ; i< records.length;i++){
                  var record = records[i]
                  if (record.get('quantity')  > record.get('stock_quantity') ){
                    Ext.MessageBox.show({
                      title: '提示',
                      msg: "您要调拨的货品数量有大于当前仓存数量的，请检查后提交！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                    return;
                    break;
                  }
                }
                    
                this.disable();
                var allJsonStr = transferFormPanel.getForm().getValues();
                allJsonStr = Ext.JSON.encode(allJsonStr);
                allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
                allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                //alert(allJsonStr);
                Ext.Ajax.request({
                  url : '/transfer_order/create',
                  success : function (result, request) {
                    newTransferWin.destroy();
                  },
                  failure : function (result, request){
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "通讯失败，请从新操作",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                    newTransferWin.destroy();
                  },
                  method : 'POST',
                  params : {
                    data : Ext.JSON.encode(allJsonStr),
                    authenticity_token: authToken.getValue()
                  }
                });
              }
            }
          }
        });

        //临时保存按钮
        var tempSaveButton = Ext.create('Ext.Button', {
          text: '暂存',
          tooltip: '暂时保存销售订单。',
          iconCls: 'temp-save',
          handler: function(){
            //同仓库不能调拨
            if(fromWarehouse.getValue() == toWarehouse.getValue() ){
              Ext.MessageBox.alert('提示', "同仓不能调拨！");
              return;
            }
            //首先把临时变量设置为1
            temporary.setValue(1);

            if (transferFormPanel.form.isValid()){

              var productsJsonStr = gridStoreToJson(transferOrderDetailDS,rejectKeyArray);
              if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              //没有添加产品，则提示
              if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //再取得一次库存
              checkStockButton.handler();
              //检查一下，如果要调拨的货比仓库的库存还要，就提示
              var records = transferOrderDetailDS.getRange(0,transferOrderDetailDS.getCount());
              for (var i = 0 ; i< records.length;i++){
                var record = records[i]
                if (record.get('quantity')  > record.get('stock_quantity') ){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您要调拨的货品数量有大于当前仓存数量的，请检查后提交！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                  break;
                }
              }

                
              this.disable();
              var allJsonStr = transferFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

              Ext.Ajax.request({
                url : '/transfer_order/create',
                success : function (result, request) {
                  //Ext.MessageBox.alert("提示","提交成功");
                  newTransferWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newTransferWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });
        
        //关闭
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newTransferWin.destroy();
          }
        });
        
        var transferFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 55,
            labelAlign: 'right'
          },
          width: '945',
          frame : true,
          url: '/transferOrder/create',
          method: 'GET',
          items: [{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .35,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [fromWarehouse]
                }, {
                  columnWidth: .35,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [toWarehouse]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [actionDate]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [transferOrderDetailGrid]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [desc]
                }]
            },temporary],
          buttons: [checkStockButton,transferButton,tempSaveButton,closeButton]
        });
        transferFormPanel.render('new_transfer_form');

        function checkStockQuantity(){
          
        }
      })
    </script>
  </head>
  <body>
    <div id="new_transfer_form"></div>
  </body>
</html>
